// 添加错误处理工具
const handleError = (error, customMessage) => {
    console.error(customMessage, error);
    if (error.response) {
        // 服务器返回错误
        return error.response.json().then(data => {
            throw new Error(data.message || customMessage);
        });
    }
    throw new Error(customMessage);
};

// API接口封装
const API = {
    baseUrl: 'http://localhost:8080/api',
    
    // 添加通用请求处理函数
    async request(url, options = {}) {
        try {
            Debug.api(options.method || 'GET', url, options.body);
            
            const response = await fetch(this.baseUrl + url, {
                ...options,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    ...options.headers
                },
                mode: 'cors',
                credentials: 'include'
            });

            if (!response.ok) {
                const errorText = await response.text();
                Debug.error('API请求失败:', response.status, errorText);
                throw new Error(`请求失败: ${response.status} ${errorText}`);
            }

            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return await response.json();
            }
            return null;
        } catch (error) {
            Debug.error('API请求失败:', error);
            throw error;
        }
    },

    // 宿舍楼相关接口
    buildings: {
        async getAll() {
            try {
                const buildings = await API.request('/buildings');
                Debug.log('获取到的宿舍楼数据:', buildings);
                return buildings || [];
            } catch (error) {
                Debug.error('获取宿舍楼列表失败:', error);
                return [];
            }
        },
        create: async (building) => {
            return await API.request('/buildings', {
                method: 'POST',
                body: JSON.stringify(building)
            });
        },
        getById: async (id) => {
            return await API.request(`/buildings/${id}`);
        },
        update: async (id, building) => {
            return await API.request(`/buildings/${id}`, {
                method: 'PUT',
                body: JSON.stringify(building)
            });
        },
        delete: async (id) => {
            try {
                Debug.log('删除宿舍楼:', id);
                await API.request(`/buildings/${id}`, {
                    method: 'DELETE'
                });
                Debug.log('删除宿舍楼成功');
                return true;
            } catch (error) {
                Debug.error('删除宿舍楼失败:', error);
                throw error;
            }
        }
    },

    // 房间相关接口
    rooms: {
        getByBuilding: async (buildingId) => {
            return await API.request(`/rooms/building/${buildingId}`);
        },
        create: async (room) => {
            return await API.request('/rooms', {
                method: 'POST',
                body: JSON.stringify(room)
            });
        },
        update: async (id, room) => {
            return await API.request(`/rooms/${id}`, {
                method: 'PUT',
                body: JSON.stringify(room)
            });
        },
        delete: async (id) => {
            try {
                Debug.log('开始删除房间:', id);
                const response = await fetch(`${API.baseUrl}/rooms/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Accept': 'application/json'
                    }
                });

                if (!response.ok) {
                    const errorMessage = response.headers.get('X-Error-Message') || 
                        `HTTP error! status: ${response.status}`;
                    throw new Error(errorMessage);
                }

                Debug.log('删除房间成功');
                return true;
            } catch (error) {
                Debug.error('删除房间失败:', error);
                throw error;
            }
        }
    },

    // 学生相关接口
    students: {
        getAll: async () => {
            return await API.request('/students');
        },
        getById: async (id) => {
            try {
                Debug.log('获取学生详情:', id);
                const student = await API.request(`/students/${id}`);
                Debug.log('获取到的学生详情:', student);
                return student;
            } catch (error) {
                Debug.error('获取学生详情失败:', error);
                throw error;
            }
        },
        getByRoom: async (roomId) => {
            return await API.request(`/students/room/${roomId}`);
        },
        create: async (student) => {
            return await API.request('/students', {
                method: 'POST',
                body: JSON.stringify(student)
            });
        },
        update: async (id, student) => {
            return await API.request(`/students/${id}`, {
                method: 'PUT',
                body: JSON.stringify(student)
            });
        },
        delete: async (id) => {
            await API.request(`/students/${id}`, {
                method: 'DELETE'
            });
        },
        search: async (keyword) => {
            try {
                Debug.log('搜索学生:', keyword);
                const students = await API.request(`/students/search?keyword=${encodeURIComponent(keyword)}`);
                Debug.log('搜索到的学生:', students);
                return students || [];
            } catch (error) {
                Debug.error('搜索学生失败:', error);
                throw error;
            }
        }
    },

    // 卫生检查记录相关接口
    hygiene: {
        getByRoom: async (roomId) => {
            return await API.request(`/hygiene-records/room/${roomId}`);
        },
        create: async (record) => {
            return await API.request('/hygiene-records', {
                method: 'POST',
                body: JSON.stringify(record)
            });
        },
        delete: async (id) => {
            try {
                Debug.log('删除卫生检查记录:', id);
                const response = await fetch(`${API.baseUrl}/hygiene-records/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Accept': 'application/json'
                    }
                });

                if (!response.ok) {
                    const errorMessage = response.headers.get('X-Error-Message') || 
                        `HTTP error! status: ${response.status}`;
                    throw new Error(errorMessage);
                }

                Debug.log('删除卫生检查记录成功');
                return true;
            } catch (error) {
                Debug.error('删除卫生检查记录失败:', error);
                throw error;
            }
        }
    },

    // 违纪记录相关接口
    discipline: {
        getAll: async () => {
            try {
                Debug.log('获取所有违纪记录');
                const records = await API.request('/disciplinary-records');
                Debug.log('获取到的违纪记录:', records);
                return records || [];
            } catch (error) {
                Debug.error('获取违纪记录失败:', error);
                throw error;
            }
        },

        create: async (record) => {
            try {
                Debug.log('创建违纪记录:', record);
                const created = await API.request('/disciplinary-records', {
                    method: 'POST',
                    body: JSON.stringify(record)
                });
                Debug.log('创建违纪记录成功:', created);
                return created;
            } catch (error) {
                Debug.error('创建违纪记录失败:', error);
                throw error;
            }
        },

        delete: async (id) => {
            try {
                Debug.log('删除违纪记录:', id);
                await API.request(`/disciplinary-records/${id}`, {
                    method: 'DELETE'
                });
                Debug.log('删除违纪记录成功');
                return true;
            } catch (error) {
                Debug.error('删除违纪记录失败:', error);
                throw error;
            }
        },

        getByBuilding: async (buildingId) => {
            try {
                Debug.log('获取宿舍楼违纪记录:', buildingId);
                const records = await API.request(`/disciplinary-records/building/${buildingId}`);
                Debug.log('获取到的违纪记录:', records);
                return records || [];
            } catch (error) {
                Debug.error('获取宿舍楼违纪记录失败:', error);
                throw error;
            }
        }
    }
}; 